<template>
  <el-card class="page_card">
    <el-form :inline="true" class="form">
      <el-form-item label="类别名称：">
        <el-input v-model="data.keyword" placeholder="请输入类别名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" color="#626aef" @click="search" 
          :disabled="data.keyword?false:true">搜索</el-button>
        <el-button @click="reset" color="#626aef" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="Plus" @click="addRole">添加类别</el-button>
    <el-table border :data="data.toolTableData" row-key="id" max-height="663">
      <el-table-column label="#" align="center" type="index" :width="80"></el-table-column>
      <el-table-column label="类别名称" align="center" prop="categoryName"></el-table-column>
      <el-table-column label="类别id" align="center" prop="categoryCode"></el-table-column>
      <!-- <el-table-column label="类别图标" align="center" prop="icon"></el-table-column>
      <el-table-column label="类别图标(白)" align="center" prop="iconWhite" ></el-table-column> -->
      <el-table-column label="操作" width="270px" align="center">
        <template #="{row}">
          <el-button type="primary" link icon="View" @click="viewOrUpdateTool(row,true)">查看</el-button>
          <el-button type="primary" link icon="Edit" @click="viewOrUpdateTool(row,false)">编辑</el-button>
          <el-popconfirm :title="`确认删除${row.categoryName}吗？`" width="240px" 
            @confirm="deleteRole(row)">
            <template #reference>
              <el-button type="danger" link icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="data.currentPage"
      v-model:page-size="data.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="->,prev, pager, next, jumper,sizes,total"
      :total="data.total"
      @current-change="currentChange"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 添加类别、更新类别 -->
  <el-dialog v-model="data.addToolDialog" :title="data.toolForm.id?'更新类别':'添加类别'" width="650">
    <el-form :model="data.toolForm" :rules="data.rules" ref="formRef" label-width="130px" style="max-width: 550px">
      <el-form-item label="类别名称" prop="categoryName">
        <el-input v-model="data.toolForm.categoryName" placeholder="请输入类别名称"></el-input>
      </el-form-item>
      <el-form-item label="类别id" prop="categoryCode">
        <el-input v-model="data.toolForm.categoryCode" placeholder="请输入类别id"></el-input>
      </el-form-item>
      <el-form-item label="类别图标" prop="iconFile">
        <el-upload
          class="avatar_uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleChange">
          <img v-if="data.fileImg" :src="data.fileImg" class="avatar" />
          <el-icon v-else class="avatar_uploader_icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="类别图标(白)" prop="iconWhiteFile">
        <el-upload
          class="avatar_uploader bg_up"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleChange2">
          <img v-if="data.fileImg2" :src="data.fileImg2" class="avatar" />
          <el-icon v-else class="avatar_uploader_icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.addToolDialog = false">取消</el-button>
        <el-button type="primary" @click="save" :disabled="data.saveBtnDisabled">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref,onMounted,reactive,nextTick,onUnmounted} from 'vue'
import {reqAllTool,reqAddOrUpdateTool,reqRemoveTool} from '@/api/expand/toolApi'
import type { Tool,ToolResData } from '@/api/expand/toolType'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting'
import { reqGetImg } from '@/api/file/index'
import { blobToUrl } from '@/utils/file'

let settingStore = useLayOutSettingStore() // 模板setting仓库
let formRef = ref<any>() //form表单实例
const data = reactive({
  keyword:'',
  currentPage:1,
  pageSize:10,
  total:0,
  toolTableData:[] as Tool[],
  addToolDialog:false, //新增对话框
  toolForm:{ //新增表单
    categoryName:'', 
    categoryCode:'', 
    icon:'',
    iconWhite:'',
    iconFile:'',
    iconWhiteFile:'',
    id:'',
    version:'',
  },
  rules:{
    categoryName:[{ required: true, trigger: 'blur', message:'请输入类别名称'}],
    categoryCode:[{ required: true, trigger: 'blur', message:'请输入类别id'}],
  },
  saveBtnDisabled:false,
  fileImg:'', //上传图片后回显
  fileImg2:'', //上传图片后回显
})

onMounted(() => {
  initTableData()
})
// 图片上传
const handleChange = (file:any) => {
  data.toolForm.iconFile = file.raw //FormData格式图片
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (e) => {
    data.fileImg = (e.target?.result as string)
  }
}
const handleChange2 = (file:any) => {
  data.toolForm.iconWhiteFile = file.raw //FormData格式图片
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (e) => {
    data.fileImg2 = (e.target?.result as string)
  }
}
// 搜索
const search = ()=>{
  initTableData()
}
// 重置
const reset = ()=>{
  settingStore.refsh = !settingStore.refsh
}
// 分页器下拉事件
const currentChange = () => {
  initTableData(data.currentPage)
}
const sizeChange = ()=> {
  initTableData()
}

// 获取工具列表
const initTableData = async(pager=1)=> {
  data.currentPage = pager
  let params = {
    current:data.currentPage,
    size:data.pageSize,
    categoryName:data.keyword,
  }
  let res:ToolResData = await reqAllTool(params)
  if(res.code==200){
    data.toolTableData = res.data.records
    data.total = res.data.total
  }
}
// 新增对话框
const addRole = ()=> {
  data.addToolDialog = true
  // 清空数据
  data.fileImg = ''
  data.fileImg2 = ''
  Object.assign(data.toolForm,{
    categoryName:'', 
    categoryCode:'', 
    icon:'',
    iconWhite:'',
    id:'',
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('categoryName')
    formRef.value.clearValidate('categoryCode')
  })
}

onUnmounted(() => {
  if (data.fileImg) {  
    URL.revokeObjectURL(data.fileImg)
  } 
  if (data.fileImg2) {  
    URL.revokeObjectURL(data.fileImg2)
  } 
})

// 查看 / 编辑对话框
const viewOrUpdateTool = async(row:Tool,disabled:boolean)=> {
  data.addToolDialog = true
  data.fileImg = ''
  data.fileImg2 = ''
  // 根据文件名获取图片数据回显img
  let res = await reqGetImg(row.icon)
  let res2 = await reqGetImg(row.iconWhite)
  if (res) {
    // blob转url
    blobToUrl(res).then(dataUrl => {  
      data.fileImg = dataUrl
    }).catch(error => {ElMessage.error(error)})
  }
  if (res2) {
    // blob转url
    blobToUrl(res2).then(dataUrl => {  
      data.fileImg2 = dataUrl
    }).catch(error => {ElMessage.error(error)})
  }
  data.saveBtnDisabled = disabled
  Object.assign(data.toolForm,row)
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('categoryName')
    formRef.value.clearValidate('categoryCode')
  })
}
// 新增/编辑确认
const save = async() => {
  try{
    await formRef.value.validate()
    const formData = new FormData()
    const {iconFile,iconWhiteFile,id,categoryCode,categoryName,version} = data.toolForm
    const staticFields = {id,categoryCode,categoryName,version}
    for(const [key, value] of Object.entries(staticFields)) {  
      formData.append(key, value)
    }
    if(iconFile) {  
      formData.append('iconFile', iconFile) //上传文件处理
    }
    if(iconWhiteFile) {  
      formData.append('iconWhiteFile', iconWhiteFile) //上传文件处理
    }
    let res = await reqAddOrUpdateTool(formData)
    if(res.code==200){
      data.addToolDialog = false
      ElMessage.success(data.toolForm.id?'更新成功！':'添加成功！')
      initTableData()
    }else{
      data.addToolDialog = false
      ElMessage.error(data.toolForm.id?'更新失败！':'添加失败！')
    }
  }catch (error) {}
}
// 删除单行工具
const deleteRole = async(row:Tool)=>{
  let res = await reqRemoveTool((row.id as number),row.version)
  if(res.code==200){
    ElMessage.success('删除成功！')
    initTableData()
  }else{
    ElMessage.error('删除失败！')
  }
}
</script>

<style scoped lang="scss">
.avatar_uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>

<style>
.avatar_uploader .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar_uploader .el-upload:hover {
  border-color: #626aef;
}
.el-icon.avatar_uploader_icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px !important;
  height: 60px !important;
  text-align: center;
}
.bg_up .el-upload:last-child{
  background-color: #4D3AA5;
}
</style>

